package org.jeecg.modules.wlhy.hyzyb.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.base.controller.JeecgController;

import org.jeecg.modules.wlhy.hyvehicle.entity.HyVehicle;
import org.jeecg.modules.wlhy.hyvehicle.service.IHyVehicleService;
import org.jeecg.modules.wlhy.hyzyb.constant.ZybStatusEnum;
import org.jeecg.modules.wlhy.hyzyb.dto.DeviceInfoDTO;
import org.jeecg.modules.wlhy.hyzyb.dto.ShippingFenceDTO;
import org.jeecg.modules.wlhy.hyzyb.dto.ShippingFenceTriggerDTO;
import org.jeecg.modules.wlhy.hyzyb.entity.HyZybStatus;
import org.jeecg.modules.wlhy.hyzyb.service.IHyZybService;
import org.jeecg.modules.wlhy.shipping.constant.ShippingStatus;
import org.jeecg.modules.wlhy.shipping.service.IHyShippingNoteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Api(tags="智运宝管理")
@RestController
@RequestMapping("/hyZyb")
@Slf4j
public class ZybController extends JeecgController<HyZybStatus, IHyZybService> {

	@Autowired
	private IHyZybService hyZybService;

	@Autowired
	private IHyVehicleService hyVehicleService;

	@Autowired
	private IHyShippingNoteService shippingNoteService;

	//智运宝实时推送，智运宝触发后调用这个接口，要把接口鉴权去掉让外部程序调用。
	//{"shippingNoteNumber":"YD202305051827490009","serialNumber":"0009","device":"868120261074147","vehicleNumber":"冀FYY65R","shippingType":1,"fenceTriggerList":[{"triggerTime":1683283473000,"fenceType":1,"address":"邢台市襄都区开元北路与卫生街交叉口开元生活广场","longitude":114.52008,"latitude":37.08561,"triggerScope":1000,"notify":1,"sdk":0,"divisionCode":"130502"}]}
	@ApiOperation(value="智运宝触发实时推送",httpMethod = "POST", notes="智运宝触发实时推送")
	@PostMapping(value = "/callback")
	public Result<?> callback(@RequestBody Object obj) {
		log.warn("智运宝回调接口，{}", JSONUtil.toJsonStr(obj));
		ShippingFenceTriggerDTO shippingFenceTrigger = JSONUtil.toBean(JSONUtil.toJsonStr(obj), ShippingFenceTriggerDTO.class, true);
		if (null == shippingFenceTrigger) {
			return Result.error("智运宝推送接口数据格式错误");
		}

		return this.shippingNoteService.zybTrigger(shippingFenceTrigger);
	}


	@ApiOperation(value="智运宝列表",httpMethod = "GET", notes="智运宝列表")
	@GetMapping(value = "/list")
	public Result<?> list(@RequestParam(name="orderId") String orderId) {
		if (StrUtil.isEmpty(orderId)) {
			return Result.error("货源id不能为空");
		}

		List<HyZybStatus> zybStatusList = this.hyZybService.list(new LambdaQueryWrapper<HyZybStatus>()
				.eq(HyZybStatus::getOrderId, orderId));
		List<HyVehicle> vehicleList = this.hyVehicleService.list(new LambdaQueryWrapper<HyVehicle>().isNotNull(HyVehicle::getVehicleDevice));
//		List<HyZybStatus> resultList = new ArrayList<>();
//		vehicleList.stream().forEach(
//				vehicle-> {
//					//如果当前智运宝设备已经指派在某个货源，不在列表中显示
//					HyZybStatus hyZybStatus = null;
//					if (CollUtil.isNotEmpty(zybStatusList)) {
//						hyZybStatus = zybStatusList.stream().filter(
//								z->z.getVehicleDevice().equalsIgnoreCase(vehicle.getVehicleDevice())).findAny().orElse(null);
//					}
//
//					//智运宝状态表中如果查不到，说明这个设备没有被指派
//					if (null == hyZybStatus) {
//						HyZybStatus zyb = HyZybStatus.builder()
//								.orderId(orderId)
//								.vehicleId(vehicle.getId())
//								.vehicleDevice(vehicle.getVehicleDevice())
//								.vehicleNumber(vehicle.getVehicleNumber())
//								.shippingStatusString(ShippingStatus.已接单.name())
//								.shippingStatus(ShippingStatus.已接单.getValue())
//								.build();
//						resultList.add(zyb);
//					}
//				}
//		);

		List<DeviceInfoDTO> deviceInfoDTOS = this.hyZybService.getActiveList();

		zybStatusList.stream().forEach(
				zybStatus->{
					HyVehicle vehicle = vehicleList.stream().filter(
							v->v.getVehicleDevice().equalsIgnoreCase(zybStatus.getVehicleDevice())).findAny().orElse(null);
					if (null != vehicle) {
						zybStatus.setVehicleNumber(vehicle.getVehicleNumber());
						zybStatus.setShippingStatusString(ShippingStatus.已接单.name());
					}

					DeviceInfoDTO deviceInfoDTO = deviceInfoDTOS.stream().filter(d->d.getDevice().equals(zybStatus.getVehicleDevice())).findAny().orElse(null);
					if (null != deviceInfoDTO) {
						//设置设备状态名称
						if (ZybStatusEnum.离线.getValue().equals(deviceInfoDTO.getStatus())) {
							zybStatus.setStatusName(ZybStatusEnum.离线.getMessage());
							zybStatus.setStatus(-1);
						} else if (ZybStatusEnum.在线.getValue().equals(deviceInfoDTO.getStatus())) {
							zybStatus.setStatusName(ZybStatusEnum.在线.getMessage());
							zybStatus.setStatus(0);
						} else {
							zybStatus.setStatusName(ZybStatusEnum.未激活.getMessage());
							zybStatus.setStatus(-1);
						}
					}
				}
		);

		return Result.OK(zybStatusList);
	}


	@ApiOperation(value="终止设备",httpMethod = "DELETE", notes="终止设备")
	@DeleteMapping(value = "/cancel")
	public Result<?> cancel(@RequestParam(name="vehicleDevice") String vehicleDevice,
							@RequestParam(name="orderId") String orderId) {
		if (StrUtil.isEmpty(vehicleDevice) || StrUtil.isEmpty(orderId)) {
			return Result.error("设备id或货源id不能为空");
		}

		log.info("删除电子围栏信息,{} {}", orderId , vehicleDevice);
		return this.hyZybService.removeDevice(vehicleDevice, orderId);
	}


	@ApiOperation(value="获取企业下智运宝设备状态",httpMethod = "GET", notes="获取企业下智运宝设备状态")
	@GetMapping(value = "/getDeviceActiveList")
	public Result<?> getDeviceActiveList() {
		return Result.OK(this.hyZybService.getActiveList());
	}


	@ApiOperation(value="检查智运宝设备状态",httpMethod = "GET", notes="检查智运宝设备状态")
	@GetMapping(value = "/getZybDeviceinfo")
	public Result<?> getZybDeviceinfo(@RequestParam(name="vehicleDevice") String vehicleDevice,
                                      @RequestParam(name="orderId") String orderId,
                                      @RequestParam(name="vehicleNumber") String vehicleNumber) {
		if (StrUtil.isEmpty(vehicleDevice)) {
			return Result.error("智运宝设备号不能为空");
		}

		if (this.hyZybService.isExistInThisOrder(vehicleDevice, vehicleNumber, orderId)) {
		    return Result.error(vehicleNumber + " 设备号 " + vehicleDevice + " 已在该货源派单");
        }

		return this.hyZybService.getDeviceInfo(vehicleDevice);
	}


	//For test，这个接口用于测试
	@ApiOperation(value="终止自动围栏",httpMethod = "POST", notes="终止围栏")
	@PostMapping(value = "/cancelAutoShippingFence")
	public Result<?> cancelAutoShippingFence(@RequestBody ShippingFenceDTO shippingFenceDTO) {
		if (StrUtil.isEmpty(shippingFenceDTO.getDevice())) {
			return Result.error("设备号不能为空");
		}

		return this.hyZybService.cancelAutoShippingFence(shippingFenceDTO.getDevice());
	}

	//For test，这个接口用于测试
	@ApiOperation(value="终止围栏",httpMethod = "POST", notes="终止围栏")
	@PostMapping(value = "/cancelShippingFence")
	public Result<?> cancelShippingFence(@RequestBody ShippingFenceDTO shippingFenceDTO) {
		if (StrUtil.isEmpty(shippingFenceDTO.getShippingNoteNumber())) {
			return Result.error("运单不能为空");
		}

		return this.hyZybService.cancelShippingFence(shippingFenceDTO.getShippingNoteNumber());
	}


	//For test，这个接口用于测试
	@ApiOperation(value="获取运单轨迹",httpMethod = "POST", notes="获取运单轨迹")
	@PostMapping(value = "/getShippingTrack")
	public Result<?> getShippingTrack(@RequestBody ShippingFenceDTO shippingFenceDTO) {
		if (StrUtil.isEmpty(shippingFenceDTO.getShippingNoteNumber())) {
			return Result.error("运单不能为空");
		}

		return this.hyZybService.getShippingTrack(shippingFenceDTO.getShippingNoteNumber());
	}


}
